package com.potenza.activiti.controller;

import com.alibaba.fastjson.JSON;
import com.potenza.activiti.security.SecurityUtil;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.model.payloads.StartProcessPayload;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.model.payloads.GetTasksPayload;
import org.activiti.api.task.runtime.TaskRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("activiti")
public class ProductAuditActivitiController {

    @Autowired
    private ProcessRuntime processRuntime;//
    @Autowired
    private TaskRuntime taskRuntime;//

    @Autowired
    private SecurityUtil securityUtil;

    @GetMapping("/echo/{product_id}")
    public String echo(@PathVariable String product_id){
        return product_id;
    }

    /**
     * 开启流程，提交产品审批
     * localhost:18081/activiti/submitLoanProduct/p1/user_id_001
     * @param productId  产品ID
     * @param staffId 业务员的ID
     * @return
     */
    @GetMapping("/submitLoanProduct/{productId}/{staffId}")
    public Map submitLoanProduct(@PathVariable String productId,
                                 @PathVariable String staffId){
        securityUtil.logInAs(staffId);//

        Map resultMap = new HashMap<String,Object>();
        //String staffId = staffId;//从token获取
        String cfoId = "cfo_id_002";//数据库查询 CFO
        String ceoId = "ceo_id_003";//数据库查询CEO
        //开始流程
        Map vars = new HashMap<String,String>();//关联用户
        vars.put("staff_id",staffId);//当前用户
        vars.put("cfo_id",cfoId);//查询CFO
        vars.put("ceo_id",ceoId);//查询CEO
        Map businessKeyMap = new HashMap();
        businessKeyMap.put("type","productAudit");
        businessKeyMap.put("productId",productId);
        String businessKey = JSON.toJSONString(businessKeyMap);//当前用户创建的产品

        StartProcessPayload myProcess_1 = ProcessPayloadBuilder
                .start()
                .withProcessDefinitionKey("productAudit")//指定的流程，配置文件里面流程ID
                .withVariables(vars)
                .withBusinessKey(businessKey)//关联业务,自定义
                .build();
        ProcessInstance pi = processRuntime.start(myProcess_1);
        System.out.println("流程实例ID：" + pi.getId());//流程实例ID：f
        resultMap.put("ProcessInstanceId",pi.getId());

        GetTasksPayload getTaskPayload = TaskPayloadBuilder
                .tasks()
                .withProcessInstanceId(pi.getId())//查询条件  流程ID
                .withAssignee(staffId)//用户
                .build();
        Page<Task> taskPage = taskRuntime.tasks(
                Pageable.of(0, 10),getTaskPayload);

        if (taskPage.getTotalItems() > 0) {
            for (Task task : taskPage.getContent()) {
                System.out.println("任务：" + task);
                resultMap.put("taskId",task.getId());
                //taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
                taskRuntime.complete(
                        TaskPayloadBuilder
                                .complete()
                                .withTaskId(task.getId())
                                .build());
            }
        }

        return resultMap;
    }

    /**
     * 自行分页处理
     * 查看待办事项
     * @param userId
     * @return
     */
    @GetMapping("/searchUserTaskList/{userId}")
    public List<Task> searchUserTaskList(@PathVariable String userId) {

        securityUtil.logInAs(userId);
        GetTasksPayload getTaskPayload = TaskPayloadBuilder
                .tasks()
                .withAssignee(userId).build();
        Page<Task> taskPage = taskRuntime.tasks(
                Pageable.of(0, 1000),getTaskPayload);

        return taskPage.getContent();
    }

    @GetMapping("/getBusinessInfo/{taskId}/{userId}")
    //点击详情
    public String getBusinessInfo(@PathVariable String taskId,
                                  @PathVariable String userId) {

        securityUtil.logInAs(userId);

        Task task = taskRuntime.task(taskId);
        String businessKey = "";
        if(task!=null){
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = processRuntime.processInstance(processInstanceId);
            businessKey = processInstance.getBusinessKey();

            System.out.println("businessKey=" + businessKey);
        }
        return businessKey;
    }

    @GetMapping("/reSubmitLoanProduct/{taskId}/{staffId}")
    public Task reSubmitLoanProduct(@PathVariable String taskId,
                                    @PathVariable String staffId) {

        securityUtil.logInAs(staffId);
        Task task = taskRuntime.task(taskId);
        if(task!=null){
            taskRuntime.complete(
                    TaskPayloadBuilder
                            .complete()
                            .withTaskId(task.getId())
                            .build());
        }
        return task;
    }

    @GetMapping("/CFOAudit/{taskId}/{cfoId}/{success}")
    public Task CFOAudit(@PathVariable String taskId,
                         @PathVariable String cfoId,
                         @PathVariable boolean success) {

        securityUtil.logInAs(cfoId);
        Task task = taskRuntime.task(taskId);

        if(task!=null){
            taskRuntime.complete(
                    TaskPayloadBuilder
                            .complete()
                            .withTaskId(task.getId())
                            .withVariable("cfoAuditSuccess",success)
                            .build());
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = processRuntime.processInstance(processInstanceId);
            System.out.println("processInstance Status"+processInstance.getStatus());
        }
        return task;
    }

    @GetMapping("/CEOAudit/{taskId}/{ceoId}/{success}")
    public Task CEOAudit(@PathVariable String taskId,
                         @PathVariable String ceoId,
                         @PathVariable boolean success) {
        securityUtil.logInAs(ceoId);
        Task task = taskRuntime.task(taskId);

        if(task!=null){
            taskRuntime.complete(
                    TaskPayloadBuilder
                            .complete()
                            .withTaskId(task.getId())
                            .withVariable("ceoAuditSuccess",success)
                            .build());
            /*String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = processRuntime.processInstance(processInstanceId);

            System.out.println("processInstance Status"+processInstance.getStatus());*/
        }
        return task;
    }
}
